var fs = require('fs')
var spitPath = require('../config/pathConfig').spitPath
var util = require('../utility/util')

var safePathCheck = util.safePathCheck

var fileName = 'spits.data'

module.exports = {

  find: function (filter, callback) {
    safePathCheck(spitPath, fileName, function (exists) {
      if (exists) {
        var data = fs.readFileSync(spitPath + fileName)
        if (!data.length) {
          data = []
        } else {
          data = JSON.parse(data)
        }
        callback(null, data)
      } else {
        callback(null, [])
      }
    })
  },
  insert: function (body, callback) {
    safePathCheck(spitPath, fileName, function (exists) {
      var data = []
      if (exists) {
        data = JSON.parse(fs.readFileSync(spitPath + fileName))
      }
      body.createdAt = new Date()
      data.push(body)
      data = JSON.stringify(data, null, 4)
      fs.writeFile(spitPath + fileName, data, function (err) {
        if (err) {
          console.log('spitHandler insert fail. err = ' + err)
        }
        callback(null)
      })
    })
  }
}